package com.jqk.cloudzuul.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * @Author:JiangQiKun
 * @Date:2022/03/13 03:57 PM
 * Description:
 * com.jqk.cloudzuul.filterLimitFilter
 * 网关限流：令牌桶算法
 */
@Component
public class LimitFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        // -10 是最小的了
        return -10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    // 每秒向令牌桶中放入两个令牌，设置每秒的请求数
    public static  final RateLimiter RATE_LIMITER=RateLimiter.create(50);
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        if(RATE_LIMITER.tryAcquire()){
            System.out.println("通过");
            return null;
        }else {
            System.out.println("被限流");
            // 为了控制不向下面所有的过滤器走了，设置条件 ，其他过滤器 (Boolean) RequestContext.getCurrentContext().get("limit");
            context.set("limit",false);
            // 只能控制不向 router 过滤器走了
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
        }
        return null;
    }
}
